<!DOCTYPE html>
<!--[if lt IE 7]><html class="ie6"><![endif]-->
<!--[if IE 7]>   <html class="ie7"><![endif]-->
<!--[if IE 8]>   <html class="ie8"><![endif]-->
<!--[if (gte IE 9)|!(IE)]><!-->
<html>
<!--<![endif]-->
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">


<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport"
	content="width=device-width,initial-scale=1,minimum-scale=1.0,maximum-scale=1.0">
<meta name="renderer" content="webkit|ie-comp|ie-stand">

<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black">
<meta name="apple-mobile-web-app-title" content="Web App">
<meta name="format-detection" content="telephone=no">

<meta name="360-site-verification"
	content="846c5179bc82eccd68fd000fb2036682">
<meta name="baidu_union_verify"
	content="a7a36270ac6900fa8bd453946a7a85c9">
<meta property="qc:admins" content="35362544462056654">
<link rel="shortcut icon" type="image/x-icon"
	href="http://jinzhe.net/images/favicon.ico">
<link rel="stylesheet" id="css"
	href="Golang%E6%89%B9%E9%87%8F%E5%8E%8B%E7%BC%A9%E5%9B%BE%E7%89%87%E5%92%8C%E6%B0%B4%E5%8D%B0%20-%20%E9%87%91%E5%93%B2%E5%8D%9A%E5%AE%A2_files/bootstrap.css"
	type="text/css">
<link rel="stylesheet"
	href="Golang%E6%89%B9%E9%87%8F%E5%8E%8B%E7%BC%A9%E5%9B%BE%E7%89%87%E5%92%8C%E6%B0%B4%E5%8D%B0%20-%20%E9%87%91%E5%93%B2%E5%8D%9A%E5%AE%A2_files/font.css"
	type="text/css">
<link rel="stylesheet"
	href="Golang%E6%89%B9%E9%87%8F%E5%8E%8B%E7%BC%A9%E5%9B%BE%E7%89%87%E5%92%8C%E6%B0%B4%E5%8D%B0%20-%20%E9%87%91%E5%93%B2%E5%8D%9A%E5%AE%A2_files/main.css"
	type="text/css">
<script>
	var PATH = "/";
</script>
<link rel="prev" href="http://jinzhe.net/post/49.html"
	title="Golang Web 框架《Gin》">
<link rel="prerender" href="http://jinzhe.net/post/49.html">
<link rel="prefetch" href="http://jinzhe.net/post/49.html">

<meta name="keywords" content="golang,压缩">
<meta name="description"
	content="前段时间想做个图片站，就用手机照了很多相片，但是要一个个用PS去压缩修改尺寸太麻烦了。最后想到了用golang去实现，算是边学边练吧。其中用到了github.com/nfnt/resize这个第三方库，仅仅支持JPG图片格式。">
<meta name="author" content="野草">
<title>Golang批量压缩图片和水印 - 金哲博客</title>
</head>
<body data-nav="2" data-autocommentpager="true">

	<div id="header" class="px">
		<div class="container">

			<div id="nav" class="pr">
				&nbsp;
				<div id="menu" class="pa">
					<div class="offset"></div>
					<ul class="down">

						<li><span class="pull-right badge">6</span> <a
							href="http://jinzhe.net/category/1/"><i
								class="fa fa-fw fa-smile-o"></i>&nbsp;记录生活</a></li>
						<li><span class="pull-right badge">24</span> <a
							href="http://jinzhe.net/category/2/"><i
								class="fa fa-fw fa-bell-o"></i>&nbsp;开发实践</a></li>
						<li><span class="pull-right badge">12</span> <a
							href="http://jinzhe.net/category/3/"><i
								class="fa fa-fw fa-folder-o"></i>&nbsp;分享干货</a></li>
						<li><span class="pull-right badge">8</span> <a
							href="http://jinzhe.net/category/5/"><i
								class="fa fa-fw fa-code"></i>&nbsp;YCKIT专栏</a>
							<ul class="sub">
								<li><a href="http://jinzhe.net/category/4/">版本更新</a></li>
								<li><a href="http://jinzhe.net/category/6/">使用帮助</a></li>
								<li><a href="http://jinzhe.net/category/7/">模板主题</a></li>
								<li><a href="http://jinzhe.net/category/8/">二次开发</a></li>
							</ul></li>
						<li class="text-center"><a href="http://jinzhe.net/readers/"><i
								class="fa fa-fw fa-user"></i>&nbsp;读者墙</a> <a
							href="http://jinzhe.net/like/"><i class="fa fa-fw  fa-heart"></i>&nbsp;点赞墙</a>

						</li>
					</ul>
				</div>

				<i class="pa bar fa fa-fw fa-bars" title="按SHIFT弹出菜单或关闭"></i>
			</div>

			<div id="nav-link" class="pa">
				<a href="http://jinzhe.net/" id="nav-home"><i
					class="fa fa-fw fa-home"></i>&nbsp;首页</a> <a
					href="http://jinzhe.net/archive/" id="nav-archive"><i
					class="fa fa-fw fa-calendar"></i>&nbsp;归档</a> <a
					href="http://jinzhe.net/music/" id="nav-music"><i
					class="fa fa-fw fa-music"></i>&nbsp;音乐</a> <a
					href="http://jinzhe.net/say/" id="nav-say"><i
					class="fa fa-fw fa-book"></i>&nbsp;留言</a>

			</div>
			<div class="pull-right" id="user">
				<ul class="nav navbar-nav">
					<li><a href="http://jinzhe.net/login/">登录</a></li>
					<li><a href="http://jinzhe.net/join/">注册</a></li>
				</ul>
			</div>
		</div>
	</div>
	<div style="height: 50px"></div>

	<div class="container">
		<div class="row">

			<div class="col-xs-12 col-md-8 col-lg-8">

				<article>
					<h1>Golang批量压缩图片和水印</h1>
					<p class="post-tip">
						<span class="pull-right">发布于：2015-03-01 11:32</span> 阅读：<abbr
							title="该文一共被浏览了160次">160</abbr> 次 , 作者：<abbr>野草</abbr> , 标签：<a
							href="http://jinzhe.net/tag/golang/">golang</a> <a
							href="http://jinzhe.net/tag/%E5%8E%8B%E7%BC%A9/">压缩</a>
					</p>
					<div class="post-content">
						<p>前段时间想做个图片站，就用手机照了很多相片，但是要一个个用PS去压缩修改尺寸太麻烦了。最后想到了用golang去实现，算是边学边练吧。其中用到了github.com/nfnt/resize这个第三方库，仅仅支持JPG图片格式。</p>
						<pre class="prettyprint">package main

import (
	"fmt"
	"github.com/nfnt/resize"
	"image"
	"image/draw"
	"image/jpeg"
	"image/png"
	"io/ioutil"
	"log"
	"math/rand"
	"os"
	"runtime"
	"strconv"
	"strings"
	"time"
)

func main() {
	runtime.GOMAXPROCS(runtime.NumCPU())
	cmd("data/")
	fmt.Println("OK!")
}

// 执行操作
func cmd(path string) {
	files, _ := ioutil.ReadDir(path)
	for _, file := range files {
		if file.IsDir() {
			fmt.Println("目录" + file.Name())
			cmd(path + file.Name() + "/")
		} else {
			if strings.Contains(strings.ToLower(file.Name()), ".jpg") {
				// 随机名称
				to := path + random_name() + ".jpg"

				origin := path + file.Name()

				fmt.Println("正在处理" + origin + "&gt;&gt;&gt;" + to)

				cmd_resize(origin, 2048, 0, to)

				defer os.Remove(origin)
			}

		}
	}
}

// 改变大小
func cmd_resize(file string, width uint, height uint, to string) {
	// 打开图片并解码
	file_origin, _ := os.Open(file)
	origin, _ := jpeg.Decode(file_origin)
	defer file_origin.Close()

	canvas := resize.Resize(width, height, origin, resize.Lanczos3)

	file_out, err := os.Create(to)
	if err != nil {
		log.Fatal(err)
	}
	defer file_out.Close()

	jpeg.Encode(file_out, canvas, &amp;jpeg.Options{80})

	// cmd_watermark(to, strings.Replace(to, ".jpg", "@big.jpg", 1))
	cmd_thumbnail(to, 480, 360, strings.Replace(to, ".jpg", "@small.jpg", 1))
}

func cmd_thumbnail(file string, width uint, height uint, to string) {
	// 打开图片并解码
	file_origin, _ := os.Open(file)
	origin, _ := jpeg.Decode(file_origin)
	defer file_origin.Close()

	canvas := resize.Thumbnail(width, height, origin, resize.Lanczos3)
	file_out, err := os.Create(to)
	if err != nil {
		log.Fatal(err)
	}
	defer file_out.Close()

	jpeg.Encode(file_out, canvas, &amp;jpeg.Options{80})
}

// 水印
func cmd_watermark(file string, to string) {
	// 打开图片并解码
	file_origin, _ := os.Open(file)
	origin, _ := jpeg.Decode(file_origin)
	defer file_origin.Close()

	// 打开水印图并解码
	file_watermark, _ := os.Open("watermark.png")
	watermark, _ := png.Decode(file_watermark)
	defer file_watermark.Close()

	//原始图界限
	origin_size := origin.Bounds()

	//创建新图层
	canvas := image.NewNRGBA(origin_size)
	// 贴原始图
	draw.Draw(canvas, origin_size, origin, image.ZP, draw.Src)
	// 贴水印图
	draw.Draw(canvas, watermark.Bounds().Add(image.Pt(30, 30)), watermark, image.ZP, draw.Over)

	//生成新图片
	create_image, _ := os.Create(to)
	jpeg.Encode(create_image, canvas, &amp;jpeg.Options{95})
	defer create_image.Close()
}

// 随机生成文件名
func random_name() string {
	rand.Seed(time.Now().UnixNano())
	return strconv.Itoa(rand.Int())
}
</pre>
						<p>
							<img
								src="Golang%E6%89%B9%E9%87%8F%E5%8E%8B%E7%BC%A9%E5%9B%BE%E7%89%87%E5%92%8C%E6%B0%B4%E5%8D%B0%20-%20%E9%87%91%E5%93%B2%E5%8D%9A%E5%AE%A2_files/4BA95D16584B5AF6C810079A26E18F7B.png">
						</p>
					</div>




					<div id="like-user" class="text-center">
						<a title="" data-original-title=""
							href="http://jinzhe.net/user/2/" class="tip"
							data-toggle="tooltip" data-title="不吃怪叔叔的糖觉得很赞"><img
							src="Golang%E6%89%B9%E9%87%8F%E5%8E%8B%E7%BC%A9%E5%9B%BE%E7%89%87%E5%92%8C%E6%B0%B4%E5%8D%B0%20-%20%E9%87%91%E5%93%B2%E5%8D%9A%E5%AE%A2_files/2.jpg"></a>
						<a title="" data-original-title=""
							href="http://jinzhe.net/user/14/" class="tip"
							data-toggle="tooltip" data-title="sole觉得很赞"><img
							src="Golang%E6%89%B9%E9%87%8F%E5%8E%8B%E7%BC%A9%E5%9B%BE%E7%89%87%E5%92%8C%E6%B0%B4%E5%8D%B0%20-%20%E9%87%91%E5%93%B2%E5%8D%9A%E5%AE%A2_files/14.jpg"></a>
					</div>

					<div class="post-like text-center">
						<a title="" data-original-title="" id="like" class="cp tip"
							data-id="50"><i class="fa  fa-heart fa-fw"></i>&nbsp;我要点赞 (<span>2</span>)</a>
						<a
							href="javascript:void(window.open('http://sns.qzone.qq.com/cgi-bin/qzshare/cgi_qzshare_onekey?url='+encodeURIComponent(document.location.href)));"
							title="分享到QQ空间" rel="nofollow"><i class="fa fa-qq fa-fw"></i>&nbsp;QQ空间</a>
						<a
							href="javascript:(function(){window.open('http://v.t.sina.com.cn/share/share.php?title='+encodeURIComponent(document.title)+'&amp;url='+encodeURIComponent(location.href)+'&amp;source=bookmark');})()"
							title="分享到新浪微博" rel="nofollow"><i class="fa fa-weibo fa-fw"></i>&nbsp;新浪微博</a>


					</div>


					<div class="text-center hidden-xs"
						style="padding: 10px; color: #999">使用键盘按键“←”和“→”可以快速切换上下篇</div>

					<div class="post-nav">
						<div class="item">
							上一篇：<a href="http://jinzhe.net/post/49.html">Golang Web
								框架《Gin》</a>
						</div>
					</div>

				</article>
				<div class="post-ad"></div>

				<div class="post-comment" data-post-id="50"
					data-comment-count="1000">
					<div id="comment-content">
						<textarea placeholder="此处输入评论内容"></textarea>
					</div>
					<div class="text-right">
						<div id="comment-tip" class="pull-left">健康文明上网，创建和谐环境</div>
						<div id="comment-button" class="cp" data-check="1"
							data-uniqid="a6a815552e5cc7861652a2b4409bb345"
							data-interval-timeout="5" data-parent-id="0" data-post-id="50"
							data-category-id="2">
							<i class="fa fa-edit fa-fw"></i>提交评论
						</div>
					</div>
					<div id="comment-loop"></div>
					<div class="text-center">
						<div id="more" class="cp" style="display: none">更多</div>
					</div>
					<br>
					<br>
					<script type="text/template-x" id="comment-template">
		<div class="comment-item">
			<p>
						<strong>~name~</strong> / ~time~ / ~ip~ 
	
			</p>
			<div class="comment-content">
			~content~
			~admin~
			~reply~
			</div>
		</div>

	</script>
					<script type="text/template-x" id="comment-reply-template">
	<div class="reply-item"><strong>~name~</strong>：~content~&nbsp;<span class="ip">~ip~</span>&nbsp;<span class="time">~time~</span></div>
	</script>
				</div>
			</div>
			
			
			
			<div class="col-xs-12 col-md-4" id="right">
				<h3 class="title">
					搜索<span>&nbsp;/&nbsp;SEARCH</span>
				</h3>
				<div role="search" id="search" data-title="请输入关键字">
					<div class="form-group pr">
						<input id="keyword" class="form-control" placeholder="请输入关键字"
							type="text"> <i class="fa fa-search pa cp"
							style="right: 10px; top: 10px"></i>
					</div>
				</div>


				<div class="tags">

					<a class="btn btn-tag" type="button"
						href="http://jinzhe.net/tag/YCKIT/">YCKIT <span class="badge">8</span></a>

					<a class="btn btn-tag" type="button"
						href="http://jinzhe.net/tag/MAC/">MAC <span class="badge">6</span></a>

					<a class="btn btn-tag" type="button"
						href="http://jinzhe.net/tag/chrome/">chrome <span
						class="badge">3</span></a> <a class="btn btn-tag" type="button"
						href="http://jinzhe.net/tag/Swift/">Swift <span class="badge">3</span></a>

					<a class="btn btn-tag" type="button"
						href="http://jinzhe.net/tag/golang/">golang <span
						class="badge">2</span></a> <a class="btn btn-tag" type="button"
						href="http://jinzhe.net/tag/mysql/">mysql <span class="badge">2</span></a>

					<a class="btn btn-tag" type="button"
						href="http://jinzhe.net/tag/Audio/">Audio <span class="badge">2</span></a>

					<a class="btn btn-tag" type="button"
						href="http://jinzhe.net/tag/HTML5/">HTML5 <span class="badge">2</span></a>

					<a class="btn btn-tag" type="button"
						href="http://jinzhe.net/tag/JS/">JS <span class="badge">2</span></a>

					<a class="btn btn-tag" type="button"
						href="http://jinzhe.net/tag/lnmp/">lnmp <span class="badge">2</span></a>
				</div>
				<a href="http://yckit.com/" target="_blank"
					style="display: block; margin-top: 10px; padding: 10px 0; background: #9EB360; color: #E9EFD9; font-size: 3em; line-height: 80px; border-radius: 2px;"
					class="text-center">野草工坊</a>
				<div class="" id="right_pin">
					<h3 class="title">
						相关内容<span>&nbsp;/&nbsp;RELATED</span>
					</h3>
					<ul class="list">
						<li><a href="http://jinzhe.net/post/4.html">MAC系统下压缩ZIP忽略“__MACOSX”或“.DS_Store”文件</a></li>
						<li><a href="http://jinzhe.net/post/49.html">Golang Web
								框架《Gin》</a></li>
					</ul>
				</div>
				<div id="right_px"></div>
			</div>

		</div>
	</div>

	<div id="footer">
		<div class="container">

			<div class="pull-left" id="footer-left">
				<a href="http://jinzhe.net/page/2.html">免责声明</a>&nbsp;-&nbsp; <a
					href="http://jinzhe.net/page/1.html">关于本站</a>
			</div>
			<div class="pull-right" id="footer-right">
				<a href="http://yckit.com/" title="本站基于 YCKIT v4.2.1 驱动"
					target="_blank">YCKIT v4.2.1</a>&nbsp;©&nbsp;2012~2015&nbsp;<b>金哲博客</b>
				<span id="footer-right-line"> &nbsp;/&nbsp; <a
					href="http://www.miitbeian.gov.cn/">蜀ICP备14010229号-2</a>
					&nbsp;/&nbsp; <script
						src="Golang%E6%89%B9%E9%87%8F%E5%8E%8B%E7%BC%A9%E5%9B%BE%E7%89%87%E5%92%8C%E6%B0%B4%E5%8D%B0%20-%20%E9%87%91%E5%93%B2%E5%8D%9A%E5%AE%A2_files/stat.php"
						language="JavaScript"></script>
					<script
						src="Golang%E6%89%B9%E9%87%8F%E5%8E%8B%E7%BC%A9%E5%9B%BE%E7%89%87%E5%92%8C%E6%B0%B4%E5%8D%B0%20-%20%E9%87%91%E5%93%B2%E5%8D%9A%E5%AE%A2_files/core.php"
						charset="utf-8" type="text/javascript"></script><a
					href="http://www.cnzz.com/stat/website.php?web_id=4072237"
					target="_blank" title="站长统计">站长统计</a>
				</span>
			</div>
			<div class="clearfix"></div>
		</div>
	</div>

	<div style="display: none;" data-original-title="返回顶部" id="totop"
		title="" data-placement="left" class="px text-center cp tip">
		<i class="fa fa-angle-up"></i>
	</div>



	<script
		src="Golang%E6%89%B9%E9%87%8F%E5%8E%8B%E7%BC%A9%E5%9B%BE%E7%89%87%E5%92%8C%E6%B0%B4%E5%8D%B0%20-%20%E9%87%91%E5%93%B2%E5%8D%9A%E5%AE%A2_files/jquery_002.js"></script>
	<script
		src="Golang%E6%89%B9%E9%87%8F%E5%8E%8B%E7%BC%A9%E5%9B%BE%E7%89%87%E5%92%8C%E6%B0%B4%E5%8D%B0%20-%20%E9%87%91%E5%93%B2%E5%8D%9A%E5%AE%A2_files/jquery.js"></script>
	<script
		src="Golang%E6%89%B9%E9%87%8F%E5%8E%8B%E7%BC%A9%E5%9B%BE%E7%89%87%E5%92%8C%E6%B0%B4%E5%8D%B0%20-%20%E9%87%91%E5%93%B2%E5%8D%9A%E5%AE%A2_files/bootstrap.js"></script>
	<script
		src="Golang%E6%89%B9%E9%87%8F%E5%8E%8B%E7%BC%A9%E5%9B%BE%E7%89%87%E5%92%8C%E6%B0%B4%E5%8D%B0%20-%20%E9%87%91%E5%93%B2%E5%8D%9A%E5%AE%A2_files/main.js"></script>
	<script
		src="Golang%E6%89%B9%E9%87%8F%E5%8E%8B%E7%BC%A9%E5%9B%BE%E7%89%87%E5%92%8C%E6%B0%B4%E5%8D%B0%20-%20%E9%87%91%E5%93%B2%E5%8D%9A%E5%AE%A2_files/_tts_browser_center.js"
		data-message="1" data-version="1.4.7" data-browser="firefox"
		data-source="Firefox" data-guid="0000000041848A75AD38CD51146F3797"
		data-id="0011000820131018" charset="utf-8" type="text/javascript"
		id="J---TK-load"></script>
	<div id="TK-log">
		<img style="display: none;"
			src="Golang%E6%89%B9%E9%87%8F%E5%8E%8B%E7%BC%A9%E5%9B%BE%E7%89%87%E5%92%8C%E6%B0%B4%E5%8D%B0%20-%20%E9%87%91%E5%93%B2%E5%8D%9A%E5%AE%A2_files/statistics.txt"
			height="0" width="0">
	</div>
</body>
</html>